<?php

declare(strict_types=1);

namespace app\admin\controller;

use thans\jwt\facade\JWTAuth;
use app\BaseController;
use app\admin\model\Admin;

class Login extends BaseController
{
    /**
     * 处理用户登录逻辑
     * 
     * @return Array
     */
    public function index()
    {
        $params = $this->request->param();
        $DBadmin = new Admin();
        $info = $DBadmin->where('username', $params['username'])->find();
        // 如果查找不到用户名，用户名错误
        if (!$info) {
            return result(null, '用户名错误', 401);
        }
        // 如果密码不对，则用户名或者密码错误
        if ($info['password'] != $params['password']) {
            return result(null, '用户名或者密码错误', 401);
        }
        // 用户名和密码都正确的话就生成并存储token
        $token = JWTAuth::builder(['uid' => $info['id']]);

        return result(['token' => "bearer $token", 'username' => $info['username'], 'id' => $info['id'], 'avatar' => $info['avatar'], 'mobile' => $info['mobile'], 'nickname' => $info['nickname'], 'gender' => $info['gender'], 'occupation' => $info['occupation'], 'city' => $info['city'], 'birthday' => $info['birthday']], '登录成功');
    }
}
